package com.yc.myFilterFactory;

import com.yc.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Component;

/**
 * 局部过滤器
 * @author zwei
 * @create 2024-09-10 11:00
 */
@Component
public class TokenFilterFactory extends AbstractGatewayFilterFactory<TokenFilterFactory.Config> {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    public TokenFilterFactory() {
        super(Config.class);
    }
    //此过滤器工厂生成token过滤器  只有request中的token不过期才能放行
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange,chain)->{
            //从requst中获取token
            String token = exchange.getRequest().getHeaders().getFirst("token");
            if (token==null||jwtTokenUtil.isTokenExpired(token)){
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            return chain.filter(exchange);
        };
    }

    public static class Config {
        //配置属性
    }
}
